import mediapipe as mp
import cv2

class Hands:
    def __init__(self):
        self.mp_hands = mp.solutions.hands.Hands()

    def process(self, frame):
        # 将frame的BGR图像转换为RGB图像
        frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
        # 处理RGB图像并返回手部关键点结果
        results = self.mp_hands.process(frame_rgb)

        # 检查是否有手部关键点
        if results.multi_hand_landmarks:
            for hand_landmarks in results.multi_hand_landmarks:
                # 绘制手部关键点
                mp.solutions.drawing_utils.draw_landmarks(
                    image=frame,
                    landmark_list=hand_landmarks,
                    connections=mp.solutions.hands.HAND_CONNECTIONS
                )

        return frame

if __name__ == '__main__':
    mp_hands = Hands()
    cap = cv2.VideoCapture(0)
    while cap.isOpened():
        ret, frame = cap.read()
        if not ret:
            break
        frame = mp_hands.process(frame)
        cv2.imshow('hands', frame)
        key = cv2.waitKey(1)
        if key == 27:  # 按下ESC键退出
            break

    cap.release()
    cv2.destroyAllWindows()
